import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '../views/login/index.vue'
// import Layout from '../views/Layout/index.vue'
// import Articles from '../views/articles/index.vue'
// import Image from '../views/image/index.vue'
// import Add from '../views/articles/add.vue'
// import Comment from '../views/comment/index.vue'
// import Page404 from '../views/page/index.vue'
// import Welcome from '../views/welcome/index.vue'
// import ArticlesEdit from '../views/articles/edit.vue'
// import Fans from '../views/fans/index.vue'
// import Setting from '../views/setting/index.vue'
const Login = () => import('../views/login/index.vue')
const Layout = () => import('../views/Layout/index.vue')
const Articles = () => import('../views/articles/index.vue')
const Image = () => import('../views/image/index.vue')
const Add = () => import('../views/articles/add.vue')
const Comment = () => import('../views/comment/index.vue')
const Page404 = () => import('../views/page/index.vue')
const Welcome = () => import('../views/welcome/index.vue')
const ArticlesEdit = () => import('../views/articles/edit.vue')
const Fans = () => import('../views/fans/index.vue')
const Setting = () => import('../views/setting/index.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    children: [
      { path: '/welcome', name: 'Welcome', component: Welcome },
      { path: '/articles', name: 'Articles', component: Articles },
      { path: '/image', name: 'Image', component: Image },
      { path: '/add', name: 'Add', component: Add },
      { path: '/comment', name: 'Comment', component: Comment },
      { path: '/articlesedit/:id', name: 'ArticlesEdit', component: ArticlesEdit },
      { path: '/fans', name: 'Fans', component: Fans },
      { path: '/setting', name: 'Setting', component: Setting }
    ]
  },
  {
    path: '*',
    name: 'Page404',
    component: Page404
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫
// 作用： 页面权限控制
// 1.当访问的页面 不是login登录页面，则判断token是否存在
// 2.存在，则允许跳转 next() ,否则 不允许跳转，并回到登录页面
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('tokenStr')
  if (to.path !== '/login') {
    if (token) {
      next()
    } else {
      alert('请先登录')
      next('/login')
    }
  } else {
    next()
  }
})

export default router
